﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using OT.Module.Model;
using OT.Module.DAL;
using OT.Common;
using OT.Dev;

using DevExpress.Xpo;

namespace OT.Module.BLL
{
    [DataObject()]
    public class Category_BLL : BaseBLL<Category, Category_DAL>
    {
        public Category_BLL(Session xpo)
        {
            XpoSession = xpo;
        }

        #region DataObject Method 

        // 与表格密切相关的数据处理

        #region Select
        [DataObjectMethod(DataObjectMethodType.Select)]
        public XPCollection<Category> Select(string parentKey, string companyId)
        {
            string parentId = parentKey!=null && !parentKey.Equals(companyId) ? parentKey : string.Empty ;

            if (parentId == "0")
                return GetAll();
            else
                return new Category_DAL().GetChildCategorys(XpoSession, parentId);
        }

        #endregion
        
        #region Insert

        [DataObjectMethod(DataObjectMethodType.Insert)]
        public void Insert(Category entity)
        {
            entity.ID = CommonService.ReturnMax();
            entity.Save();
            // XpoSession.Save(entity);
        }

        #endregion 

        #region Update

        [DataObjectMethod(DataObjectMethodType.Update)]
        public void Update(Category entity, Category original_entity)
        {
            entity.Save();
        }

        #endregion

        #region _CheckDelete

        override public bool _CheckDelete(string id, ref string error)
        {
            // TODO:作删除校验时，根据定义的表间关系自动判断是否允许删除，可排除需要关联删除的表间关系
            // 作删除时，根据定义的关联删除关系进行删除

            // 要检查数据能否被删除

            // 是否有子分类
            if (new Category_DAL().HasChilds(id))
            {
                error = "待删除分类含有子分类，删除失败！";
                return false;
            }
            return true;
        }

        #endregion

        #region GetAll

        public XPCollection<Category> GetAll()
        {
            return _SelectEntitys();
        }

        #endregion

        #endregion

        #region GetCategoryDictionary

        public Dictionary<string, List<Category>> GetCategoryDictionary()
        {
            // TODO:这里应当考虑使用缓存机制
            return BaseDictionary.GetKeyListDictionary<Category>("ParentCategory.ID", GetAll());
        }

        #endregion

        #region GetKeyDictionary

        public Dictionary<string, Category> GetKeyDictionary()
        {
            // TODO:这里应当考虑使用缓存机制
            return BaseDictionary.GetKeyDictionary<Category>("ID", GetAll());
        }

        #endregion


    }
}
